package cn.edu.dzkd.software.interceptor;

import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

@Component
public class LoginInterceptor implements HandlerInterceptor {
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        Object user = request.getSession().getAttribute("yongHu");
        System.out.println("afterCompletion----" + user + " ::: " + request.getRequestURL());
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        Object user = request.getSession().getAttribute("yongHu");
        System.out.println("postHandle----" + user + " ::: " + request.getRequestURL());
    }

    /**
     * 拦截验证，如果请求中没有用户对象，代表用户没有登录，跳转回到登录页面
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        HttpSession session = request.getSession();   // java 请求与响应之间一个连接状态
        Object user = session.getAttribute("user");
        System.out.println("preHandle----" + user + " ::: " + request.getRequestURL() + "   ----   " + request.getRequestURI());
        System.out.println("======================================session id = " + request.getSession().getId());
        System.out.println("====================================getLocalAddr = " + request.getLocalAddr());
        System.out.println("===================================getRemoteHost = " + request.getRemoteHost());
        System.out.println("===================================getRemoteAddr = " + request.getRemoteAddr());

        if (user == null) {
            request.setAttribute("msg", "无权限请先登录");
            // 获取request返回页面到登录页
            response.sendRedirect("/login/login.html");
//            request.getRequestDispatcher("/login.html").forward(request, response);
            return false;
        }
        return true;   // 放行
    }
}
